package com.ai.bitcoin.thread.pool;

import com.ai.bitcoin.common.trace.TraceUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * 任务执行器，整个应用共用一个线程池
 */
@Service
@Slf4j
public class TaskExecutor {
    private int minRequestThreads = 5;

    private int maxRequestThreads = 15;

    private ExecutorService executorService;

    @PostConstruct
    public void start() {
        executorService = new ThreadPoolExecutor(minRequestThreads, maxRequestThreads,
                600L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
    }

    @PreDestroy
    public void stop() {
        executorService.shutdown();
    }


    public void execute(final ProcessContext context, final ITask task) {
        log.info("异步执行");
        try {
            if (context != null) {
                TraceUtil.initTraceFrom(context);
            }
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        task.run();
                    } catch (Throwable e) {
                        log.error("未捕获异常：", e);
                    }
                }
            });
        } catch (RejectedExecutionException re) {
            log.error("系统超载，线程池耗尽！");
        }
    }

    public Future<?> submit(final ProcessContext context, final ITask task) {
        try {
            if (context != null) {
                TraceUtil.initTraceFrom(context);
            }
            return executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        task.run();
                    } catch (Throwable e) {
                        log.error("未捕获异常：", e);
                    }
                }
            });
        } catch (RejectedExecutionException re) {
            log.error("系统超载，线程池耗尽！");
        }
        return null;
    }

    public Future<?> submit(final ProcessContext context, final Callable callable) {
        try {
            if (context != null) {
                TraceUtil.initTraceFrom(context);
            }
            return executorService.submit(callable);
        } catch (RejectedExecutionException re) {
            log.error("系统超载，线程池耗尽！");
        }
        return null;
    }

}
